<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {useCartStore} from "@/stores/cartStore";
import {createOrder, getUserAddresses} from "@/router/api";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/userStore";
import {useOrderStore} from "@/stores/orderStore";
import {authUtilStore} from "@/utils/authStore";
import {useRoute} from "vue-router";

const route = useRoute()
const cartStore = useCartStore()
const orderStore = useOrderStore()
const authStore = authUtilStore();
const userStore = useUserStore()
const getTotalPrice = ref()
const editDialog = ref(false);
// 商品数据
const orderItems = ref<any[]>([])

// 地址数据
interface Address {
  id: number;
  accept: string;   // 收件人姓名
  telphone: string; // 联系电话
  address: string;  // 详细地址
  def: string;      // 是否默认地址 (建议改用 boolean 类型)
}

const invoice = reactive({
  title: "",
  order_info: "",
  type: "",
  tax_id: "",
  bank_card: ""
});
const tableData = ref<Array<{
  id: number;
  accept: string;
  telphone: string;
  address: string;
  def: string;
}>>([]);
const currentAddress = ref<Address>();
// 初始化购物车
onMounted(async () => {
  // 根据路由参数判断来源
  if (route.query.type === 'buyNow') {
    // 显示立即购买的商品
    orderItems.value = orderStore.tempOrderItems
    getTotalPrice.value = orderStore.tempOrderTotal // 总价
  } else {
    // 正常购物车流程
    await cartStore.fetchCart()
    orderItems.value = cartStore.cartStore
    getTotalPrice.value = cartStore.getTotalPrice.value.toFixed(2) // 总价
  }
  await getAddress()
})
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
// 切换支付方式
const payRadio = ref(1)
const changePayRadio = () => {
}
// 切换发票信息
const orderRadio = ref(0)
const changeOrderRadio = () => {
}

// 提交订单
const submitOrder = async () => {
  if (userStore.userInfo.status === '0') {
    ElMessage.warning('你已被冻结，无法提交订单');
    return;
  }
  try {
    // 生成商品清单描述
    const generateOrderInfo = () => {
      return orderItems.value
          .map(item => `${item.name}-${item.num}件`) // 格式示例: "商品A 2件"
          .join('；'); // 用换行符分隔多个商品
    };
    // 地址校验
    if (!currentAddress.value) {
      showMessage('error', '请选择收货地址');
      return;
    }

    // 发票校验（如果开了发票）
    if (orderRadio.value !== 0) {
      if (!invoice.title) {
        showMessage('error', '请输入发票抬头');
        return;
      }
      if (orderRadio.value === 2 && !(invoice.tax_id && invoice.bank_card)) {
        showMessage('error', '请完善发票信息');
        return;
      }
    }
    // 动态构建请求数据
    const orderData: any = {
      user_id: userStore.userInfo.id,
      total_money: Number(getTotalPrice.value),
      address: currentAddress.value?.address || "",
      accept: currentAddress.value?.accept || "",
      telphone: currentAddress.value?.telphone || "",
      pay_type: payRadio.value,
      items: orderItems.value.map(item => ({
        goods_id: item.goodid,
        name: item.name,
        image: item.image,
        num: item.num,
        price: Number(item.sale_price)
      }))
    }

    // 只有开发票时才添加invoice字段
    if (orderRadio.value !== 0) {
      orderData.invoice = {
        title: invoice.title,
        type: orderRadio.value,
        tax_id: invoice.tax_id,
        bank_card: invoice.bank_card,
        order_info: generateOrderInfo().slice(0, 255)
      }
    }
    // 调用后端接口提交订单
    const response = await createOrder(orderData)
    // 检查响应结构
    if (response !== null) {
      const orderStore = useOrderStore()

      // 存储订单数据到Pinia
      orderStore.setCurrentOrder({
        id: response.data.orderId,
        no: response.data.orderNo,
        total: Number(getTotalPrice.value),
        pay_type: payRadio.value
      })

      // 清空购物车
      if (route.query.type === 'buyNow') {
        orderStore.clearTempOrder() // 清空临时订单
      } else {
        await cartStore.clearCart()// 清空购物车
      }

      showMessage("success", "提交订单成功")
      authStore.active = 2
    } else {
      showMessage("error", "订单创建失败")
    }
  } catch (e) {
    console.log(e)
    showMessage("error", "提交订单失败")
  }
}


//获取地址信息
const getAddress = async () => {
  try {
    const res = await getUserAddresses(userStore.userInfo.id);
    tableData.value = (Array.isArray(res) ? res : []).map(item => ({
      id: item.id,
      accept: item.accept,
      telphone: item.telphone,
      address: [item.province, item.city, item.area, item.street].filter(part => part?.trim()).join('-'),
      def: item.def === "Y" ? "是" : "否"
    }));

    // 查找并赋值默认地址
    currentAddress.value = tableData.value.find(item => item.def === '是') || undefined;
  } catch (err) {
    showMessage('error', '获取地址失败！')
    tableData.value = [];
  }
}
//选择地址
const handleSelectAddress = (row: any) => {
  currentAddress.value = row;
}
</script>

<template>
  <!-- main -->
  <div class="content-main">
    <div class="content-main-content">
      <div class="content-main-content-title1">核对订单信息</div>
      <!-- 收货地址 -->
      <div class="content-main-content-address">
        <div class="content-main-content-title">收货信息
          <el-button plain size="small" type="primary" @click="editDialog = true" style="margin-left: 10px">更换地址
          </el-button>
        </div>

        <el-descriptions :column="2" border>
          <el-descriptions-item label-align="center" label="收件人" align="center">
            {{ currentAddress?.accept || "" }}
          </el-descriptions-item>
          <el-descriptions-item label-align="center" label="手机号" align="center">
            {{ currentAddress?.telphone || "" }}
          </el-descriptions-item>
          <el-descriptions-item label-align="center" label="地址" align="center">
            {{ currentAddress?.address || "" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <!-- 支付方式 -->
      <div class="content-main-content-pay">
        <div class="content-main-content-title">支付方式</div>
        <div>
          <el-radio-group v-model="payRadio" @change="changePayRadio" size="large">
            <el-radio :value="1" size="large">微信支付</el-radio>
            <el-radio :value="2" size="large">支付宝支付</el-radio>
            <el-radio :value="3" size="large">银行卡支付</el-radio>
          </el-radio-group>
        </div>
      </div>
      <!-- 商品清单 -->
      <div class="content-main-content-order">
        <div class="content-main-content-title">商品清单</div>
        <div class="content-main-content-order-item">
          <!-- 头部标签 -->
          <div class="card-header">
            <div>商品信息</div>
            <div>单价</div>
            <div>数量</div>
            <div>小计</div>
          </div>
          <!-- 商品列表 -->
          <div class="item">
            <el-empty v-if="!orderItems.length" :image-size="100" description="购物车还没有商品，赶紧选购吧"/>
            <div v-else class="card-body" v-for="product in orderItems">
              <div class="card-item">
                <img :src="product.image" alt="商品图片" class="card-img">
                <el-text>{{ product.name }}</el-text>
              </div>
              <div>￥{{ Number(product.sale_price).toFixed(2) }}</div>
              <div>{{ product.num }}</div>
              <div>￥{{ (Number(product.sale_price) * product.num).toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 发票信息 -->
      <div class="content-main-content-invoice">
        <div class="content-main-content-title">发票信息</div>
        <div>
          <el-radio-group v-model="orderRadio" @change="changeOrderRadio" size="large">
            <el-radio :value="0" size="large">不开发票</el-radio>
            <el-radio :value="1" size="large">个人</el-radio>
            <el-radio :value="2" size="large">企业</el-radio>
          </el-radio-group>
        </div>
        <div v-if="orderRadio !== 0" class="personal-invoice">
          <el-form :model="invoice" status-icon scroll-to-error>
            <el-form-item label="发票抬头" prop="title">
              <el-input v-model="invoice.title" placeholder="请输入发票抬头" clearable size="large"/>
            </el-form-item>
            <el-form-item label="企业税号" prop="tax_id" v-if="orderRadio===2">
              <el-input v-model="invoice.tax_id" placeholder="请输入企业税号" clearable size="large"/>
            </el-form-item>
            <el-form-item label="银行卡号" prop="bank_card" v-if="orderRadio === 2">
              <el-input v-model="invoice.bank_card" placeholder="请输入银行卡号" clearable size="large"/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 确认订单 -->
      <div class="card-footer" v-if="orderItems.length">
        <div class="btn-group">
          总计：<span style="color: #e81414;font-size: 25px">￥{{ getTotalPrice }}</span>
        </div>
        <button class="btn-primary" @click="submitOrder">确认无误，提交订单</button>
      </div>
    </div>
  </div>
  <!- 修改地址窗口 -->
  <el-dialog v-model="editDialog" title="更换地址" center draggable width="1000">
    <el-descriptions :column="3" border title="当前地址信息" style="margin-bottom: 1rem">
      <el-descriptions-item label-align="center" label="收货人" align="center">
        {{ currentAddress?.accept || "" }}
      </el-descriptions-item>
      <el-descriptions-item label-align="center" label="联系电话" align="center">
        {{ currentAddress?.telphone || "" }}
      </el-descriptions-item>
      <el-descriptions-item label-align="center" label="收货地址" align="center">
        {{ currentAddress?.address || "" }}
      </el-descriptions-item>
    </el-descriptions>
    <!--  收货地址信息  -->
    <h3>可选地址</h3>
    <el-table :data="tableData" border highlight-current-row>
      <el-table-column prop="accept" label="收货人" show-overflow-tooltip align="center" width="150"/>
      <el-table-column prop="telphone" label="联系电话" show-overflow-tooltip align="center" width="150"/>
      <el-table-column prop="address" label="收货地址" show-overflow-tooltip align="center"/>
      <el-table-column prop="def" label="是否默认地址" show-overflow-tooltip align="center" width="150"/>
      <el-table-column fixed="right" label="操作" show-overflow-tooltip align="center" width="100">
        <template #default="scope">
          <el-button size="small" @click="handleSelectAddress(scope.row)" type="primary">选择地址
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div>
        <el-button @click="editDialog = false">取消更换</el-button>
        <el-button type="primary" @click="editDialog = false">更换地址</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.personal-invoice {
  border: 1px solid #cccccc;
  padding: 10px;
}

.content-main-content-invoice {
  padding-left: 30px;
}

.btn-primary {
  background-color: #ff6a00;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
  margin: 0 30px;
}

.btn-group {
  font-weight: normal;
  font-size: 20px;
}

.card-footer {
  border-top: 1px solid blanchedalmond;
  padding-top: 10px;
  width: 100%;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: end;
  margin-bottom: 10px;
}

.card-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.card-img {
  width: 80px;
  height: 100px;
  margin-right: 20px;
}

.card-body {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ccc;
}

.card-header {
  width: 100%;
  display: flex;
  flex-direction: row;
  padding: 10px 0;
  border-bottom: 1px solid #ccc;
}

.card-header > div, .card-body > div {
  text-align: center;
}

.card-header > div:nth-child(1), .card-body > div:nth-child(1) {
  width: 42%;
  text-align: left;
  margin: 0 1%;
}

.card-header > div:nth-child(2), .card-body > div:nth-child(2) {
  color: #e81414;
  width: 12%;
  margin: 0 2%;
}

.card-header > div:nth-child(3), .card-body > div:nth-child(3) {
  width: 12%;
  margin: 0 2%;
}

.card-header > div:nth-child(4), .card-body > div:nth-child(4) {
  color: #e81414;
  width: 12%;
  margin: 0 2%;
}

.item {
  width: 100%;
  max-height: 350px;
  overflow-y: auto;
}

.item::-webkit-scrollbar {
  width: 2px;
}

.item::-webkit-scrollbar-thumb {
  background-color: #696969;
}

.content-main-content-order-item {
  border: 1px solid #ccc;
}

.content-main-content-order {
  padding-left: 30px;
}

.content-main-content-pay {
  padding-left: 30px;
}

.content-main-content-title {
  margin-top: 20px;
  margin-bottom: 10px;
  border-top: 2px solid #ff6a00;
  padding: 10px;
  font-size: 18px;
  color: #ff6a00;
  background: linear-gradient(to bottom, #f1f1f1, transparent);
}

.content-main-content-address {
  padding-left: 30px;
}

.content-main-content-title1 {
  padding: 5px 20px;
  font-size: 20px;
  background: #f2f2f2;
  border-bottom: 1px solid #ddd;
}

.content-main-content {
  border: 1px solid #ccc;
  width: 90%;
}

.content-main {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}
</style>